import {
  observable,
  action,
  computed,
  extendObservable,
  toJS,
} from 'mobx'

import { topicSchema } from '../util/variable-define'
import { get, post } from '../util/http'

const createTopic = (topic) => {
  return Object.assign({}, topicSchema, topic)
}

class Topic {
  constructor(data) {
    extendObservable(this, data)
  }

  @observable syncing = false

  @action doReply(content) {
    return new Promise((resolve, reject) => {
      post(`/topic/${this.id}/replies`, {
        needAccessToken: true,
      }, {
        content,
      })
        .then((data) => {
          debugger // eslint-disable-line
          if (data.success) {
            resolve({
              replyId: data.reply_id,
              content,
            })
          } else {
            reject()
          }
        }).catch(reject)
    })
  }
}

class TopicStore {
  @observable topics // 文章列表页话题数组

  @observable details // 所有文章详情数组

  @observable syncing

  @observable tab

  @observable createdTopics = []

  @computed get topicMap() {
    return this.topics.reduce((result, topic) => {
      result[topic.id] = topic
      return result
    }, {})
  }

  @computed get detailsMap() {
    return this.details.reduce((result, topic) => {
      result[topic.id] = topic
      return result
    }, {})
  }

  constructor({ syncing = false, topics = [], details = [], tab = null } = {}) { // eslint-disable-line
    this.syncing = syncing
    this.topics = topics.map(topic => new Topic(createTopic(topic)))
    this.details = details
    this.tab = tab
  }

  @action fetchTopics(tab) {
    return new Promise((resolve, reject) => {
      if (tab === this.tab && this.topics.length > 0) {
        resolve()
      } else {
        this.tab = tab
        this.syncing = true
        this.topics = []
        get('/topics', {
          mdrender: false,
          tab,
        }).then((resp) => {
          if (resp.success) {
            this.topics = resp.data.map((topic) => {
              return new Topic(createTopic(topic))
            })
            this.syncing = false
            resolve()
          } else {
            reject()
          }
          this.syncing = false
        }).catch((err) => {
          reject(err)
          this.syncing = false
        })
      }
    })
  }

  @action fetchTopic(topicID) {
    return new Promise((resolve, reject) => {
      if (this.detailsMap[topicID]) {
        resolve(this.detailsMap[topicID])
      } else {
        get(`/topic/${topicID}`, {
          mdrender: false,
        }).then((resp) => {
          if (resp.success) {
            console.log(resp.data)
            this.details.push(new Topic(createTopic(resp.data), true))
            this.syncing = false
            console.log(this.details)
            resolve()
          } else {
            reject()
          }
        }).catch((err) => {
          reject(err)
        })
      }
    })
  }

  @action postTopic(title, tab, content) {
    return new Promise((resolve, reject) => {
      post('/topics', {
        needAccessToken: true,
      }, {
        title, tab, content,
      })
        .then((data) => {
          console.log('接口返回数据', data)
          if (data.success) {
            const topic = {
              title,
              tab,
              content,
              id: data.topic_id,
              create_at: Date.now(),
            }
            this.createdTopics.push(new Topic(createTopic(topic)))
            resolve(topic)
          } else {
            reject(new Error(data.error_msg || '未知错误'))
          }
        })
        .catch((err) => {
          console.log('catch到一个错误')
          if (err.response) {
            reject(new Error(err.response.data.error_msg || '未知错误'))
          } else {
            reject(new Error('未知错误'))
          }
        })
    })
  }

  toJson() {
    return {
      topics: toJS(this.topics),
      syncing: toJS(this.syncing),
      details: toJS(this.details),
      tab: toJS(this.tab),
    }
  }
}

export default TopicStore
